﻿var express = require('express');
var app = express();
var fs = require("fs");
var buffer = require("buffer")
var url=require('url');
var adm_zip = require('adm-zip');
var zipper = require('zip-local');
var multipart = require('connect-multiparty');
var iconv = require('iconv-lite');  

// log 日志模块 
// var log4js = require("./log");
// app.use(log4js.useLog());

var fileList = [];
var JsonPath = '';
var CurPaht='';
var berr=true;
var Adrrs = '';
//path模块，可以生产相对和绝对路径
var path = require("path");

var bodyParser = require('body-parser');
var multer  = require('multer');
 
app.use(express.static('public'));// 可以在浏览器上直接访问这个文件下的文件 public/images/logo.png  网页访问:http://127.0.0.1:8081/images/logo.png
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('name'));


app.get('/file_query', function (request, response) {

   if(false)
   {
	   	rst = {
		first_name:request.query.name,
		last_name:request.query.path
		};
	    console.log(rst);
		response.write(request.query.name + "::"+ request.query.path);
		response.end();
		return;
   }  
	var file_Serchname = decodeURI(request.query.name);
	if(file_Serchname.length == 0)
	{
		file_Serchname='.';
	}
    var pathname = decodeURI(request.query.path);
	console.log('123'+ pathname);
    var pathnamein = pathname;
	
    var realPath = path.join(path.resolve() , "/upload/");
	realPath = path.join(realPath , pathname);
    console.log(realPath);
	pathname = realPath;
	try{
		var reg = 	new RegExp(file_Serchname);//eval('/'+Name+'/')	; // 动态生成字符串 正则匹配方式	
	}
	catch(e)
	{
		resjson = {
				   Reslut:'-2', 
				   Msg:'查询条件: ' + file_Serchname +'错误，请重新输入 ;'
				};
		console.log( resjson );
		response.end( JSON.stringify( resjson ) );
		return ;
	}
	if (pathname.charAt(pathname.length - 1) == "/") {
            //如果访问目录
			// 返回目录的目录：
			try{
			JsonPath = '';
			walkJson(pathname,file_Serchname,pathname);
			JsonPath = JsonPath.substr(0,JsonPath.length-1);
	
			JsonPath = '{"Reslut":"0","Msg":' +  "[" +  JsonPath  + "]"  + '}';
			console.log("123" + JsonPath);
			jsonstr = JsonPath;
			// response.writeHead(200,{'Content-Type' : 'text/html'});
			// response.write('<head><meta charset="utf-8"/></head>');
			response.write(jsonstr);
			response.end();
			
			return;	

			}
			catch(e)
			{
				 resjson = {
				   Reslut:'-2', 
				   Msg:'访问目录异常：'+ pathnamein +' ; 退出' 
				};
				console.log( resjson );
				response.end( JSON.stringify( resjson ) );
			}
        }
		else
		{
			try {
				fs.readFile( pathname, function (err, data) {        
			 if( err ){
				JsonPath = '';
				walkJson(pathname,file_Serchname,pathname);
				JsonPath = JsonPath.substr(0,JsonPath.length-1);
						 // resjson = {
				   // Reslut:'0', 
				   // Msg:'{' + "[" +  JsonPath  + "]"  + '}'
				// };
				// console.log( resjson );
				// response.end( JSON.stringify( resjson )  );
			 JsonPath = '{"Reslut":"0","Msg":'  + "[" +  JsonPath  + "]"  + '}';
				console.log("123" + JsonPath);
				jsonstr = JsonPath;
			// response.writeHead(200,{'Content-Type' : 'text/html'});
			// response.write('<head><meta charset="utf-8"/></head>');
				response.write(jsonstr);
				response.end();
			 }else{
				 	//var ast= 'File uploaded successfully';
					//console.log( ast );	
					var lastName = getdir(pathname);
　					response.writeHead(200,{'Content-Type' : 'text/html'});　					
					response.write(data);
					response.end();　
				}
			   });	
		
			} catch(e) 
			{
				console.log('路径访问错误！');
				 resjson = {
				   Reslut:'-3', 
				   Msg:'路径访问异常！'+ pathnamein +' ; 退出!' 
				};
				console.log( resjson );
				response.end( JSON.stringify( resjson ) );
			}
			
		}
   
		
	     
});
// 专门为检索添加的接口调用 
app.get('/file_IndexSeach',function(request, response)
{
	var file_Serchname = decodeURI(request.query.name);
	
	if(file_Serchname.length == 0)
	{
		file_Serchname='.';
	}
    var pathname = decodeURI(request.query.path);
	console.log('123'+ pathname);
    var pathnamein = pathname;
	
	
    var realPath = path.join(path.resolve() , "/upload/");
	realPath = path.join(realPath , pathname);
	console.log(realPath);
		
	if(file_Serchname == ".......")// 七个点 意味着这个是初始化检索文件的
	{
		var AllSerch = function (dirPath) {
			 var files = fs.readdirSync(dirPath);
			 if (files.length > 0)
			  for (var i = 0; i < files.length; i++) {
			   var filePath = path.join(dirPath, files[i]);
			   if (fs.statSync(filePath).isFile()) {
				   var _xml=/.zip$/i.test(filePath);
					if(_xml) // 压缩包
					{
						var urlpath = filePath;
						urlpath = urlpath.replace(/\\/g,"/");						
						//console.log(urlpath + "::AddSearchFile 参数");
						AddSearchFile(realPath,urlpath);
					}						
			   } else {
				AllSerch(filePath);
			   }
			  }			
			};
		var url = realPath + "/indexSeachfile.txt";
		fs.writeFileSync(url, "[]","utf-8");
		AllSerch(realPath);
		
	}

	pathname = realPath;
	try{
		var reg = 	new RegExp(file_Serchname);//eval('/'+Name+'/')	; // 动态生成字符串 正则匹配方式	
	}
	catch(e)
	{
		resjson = {
				   Reslut:'-2', 
				   Msg:'查询条件: ' + file_Serchname +'错误，请重新输入 ;'
				};
		console.log( resjson );
		response.end( JSON.stringify( resjson ) );
		return ;
	}
	// 打开本地文件
	var url = realPath + "/indexSeachfile.txt";	

	var IndexSeachfiledata = fs.readFileSync(url,"utf-8"); 
	//console.log(IndexSeachfiledata);
	if(IndexSeachfiledata.length < 2)
	{
		IndexSeachfiledata= '[' +IndexSeachfiledata+']';
	}	
	
	var obj = JSON.parse(IndexSeachfiledata);
	var outobj=[];
	for(var i = 0 ; i< obj.length; i++)
	{
		var filei= obj[i];
		var reg = 	new RegExp(file_Serchname);//eval('/'+Name+'/')	; // 动态生成字符串 正则匹配方式	
		if(reg.test(filei.fData)){
			var osbj={};
			osbj
			outobj.push(filei);
		}
	}
	var jsonstr = JSON.stringify(outobj);
	JsonPath = '{"Reslut":"0","Msg":' + jsonstr  + '}';
	console.log("file_IndexSeach" + JsonPath);
	jsonstr = JsonPath;	
	response.write(jsonstr);
	response.end();
});
app.get('/file_delete', function (request, response) {// 删除文件
	if(false)
   {
	   	rst = {
		first_name:request.query.name,
		last_name:request.query.path
		};
	    console.log(rst);
		response.write(request.query.name + "::"+ request.query.path);
		response.end();
		return;
   } 
   
   var paths = decodeURI(request.query.path);
   var file = decodeURI(request.query.name);
   var realPath = path.join(path.resolve() , "/upload");
	realPath = path.join(realPath , paths);
	//  如果是对bugzip 进行修改的话 那么有逻辑清理掉检索文件的
	var bdelbugzip = false;
	if(paths == "bugzip")
	{
		bdelbugzip = true;
	}
	JsonPath = "";
	berr = true;
	if(file.length == 0)// 删除目录
	{
		if(paths.length == 0) // 删除整个upload  不被允许
		{
			resjson = {
                   Reslut:'-1', 
                   Msg:'请选择删除文件或目录'
             };
		    response.end( JSON.stringify( resjson ) );
		    return;
		}
		fs.exists(realPath,function(exists)
		{
			if(!exists){
				console.log("文件夹不存在")
				 resjson = {
					   Reslut:'0', 
					   Msg:'删除目录：'+paths+' 不存在!'
				  };			
			    response.end(JSON.stringify( resjson ));
			}
			else{
				//console.log("1233"+ realPath);
				//deleteall(realPath,JsonPath);
				var rmdir = function (dirPath) {
				 var files = fs.readdirSync(dirPath);
				 if (files.length > 0)
				  for (var i = 0; i < files.length; i++) {
				   var filePath = path.join(dirPath, files[i]);
				   if (fs.statSync(filePath).isFile()) {
					fs.unlinkSync(filePath);
						if(bdelbugzip)
						{
							DelSearchFile(realPath,filePath);
						}
				   } else {
					rmdir(filePath);
				   }
				  }
				 fs.rmdirSync(dirPath);
				};

				try {
					 rmdir(realPath);
					 resjson = {
							   Reslut:'0', 
							   Msg:'删除目录：'+paths+' 成功'
						  };
					console.log(resjson);
					response.end(JSON.stringify( resjson ));
				} catch (e) {
					// JsonPath =  '{\"Reslut\":"-1",\"errMsg\":\"' + e.message + '\"}' ;
					var curworkPath = path.join(path.resolve() , "/upload");
					var emssage= e.message.replace(curworkPath,'.');
					resjson = {
							   Reslut:'-1', 
							   Msg:'删除目录: '+ paths +'失败 ;' +'{'+emssage+'}'
						  };
					console.log(resjson);
					response.end( JSON.stringify( resjson ) );
					 return;
					 //console.log(e.message);
				}
			}
		});		
	
	}
	else // 删除文件
	{
		var vfile = file;
		file = path.join(realPath , file);	
		fs.exists(file,function(exists)
		{
			if(!exists){
				console.log("文件不存在")
				 resjson = {
					   Reslut:'0', 
					   Msg:'删除文件：'+vfile+' 不存在; '
				  };			
			    response.end(JSON.stringify( resjson ));
			}
			else{
				console.log("345"+ realPath);
					
				//deletOneFile(file,response);
				fs.unlink(file, function(err){
				 if(err){
					//JsonPath =  '{\"Reslut\":"-1",\"Msg\":[{\"' + vfile  +'\":\"' + '-1' +'\"}]}' ;
					var curworkPath = path.join(path.resolve() , "/upload");
										
					var emssage= err.message.replace(curworkPath,'.');
					resjson = {
						Reslut:'-1', 
						Msg:'删除文件: '+ vfile +'失败 ;' +'{'+emssage+'}'
						  };
					console.log(JSON.stringify( resjson ) );
					response.end( JSON.stringify( resjson ) );
				 }
				 else
				 {
				   //JsonPath =  '{\"Reslut\":"0",\"Msg\":[{\"' + vfile  +'\":\"0\"}]}' ;
						resjson = {
						  Reslut:'0', 
						  Msg:'删除文件: '+ vfile +'成功 ;'
						};
					console.log(JSON.stringify( resjson ) );
					response.end( JSON.stringify( resjson ) );
					if(bdelbugzip)
					{
						DelSearchFile(realPath,vfile);
					}
				 }
				 // console.log('文件:'+vfile+'删除成功！');
				 // response.write(JsonPath);
				// response.end();
				})	
			}
		});
	}
   // response.write(resout);
   // response.end();
});
app.get('/index.htm', function (req, res) {
	//console.log('12345');
   res.sendFile( __dirname + "/" + "index.htm" );
})

app.post('/file_upload', function (req, res) {
   if(false)
   {
	   console.log(req);
	   
		var dPaht = decodeURI(req.body.path),
	    fileName = decodeURI(req.files[0].originalname),
		tempPaht = decodeURI(req.files[0].path),
		ziptype = decodeURI(req.body.ziptype);
		
		var dPaht = decodeURI(req.query.path)
		var fileName = decodeURI(req.query.name )
		res.write(fileName+ "::"+ dPaht);
		res.end();
		return;
   } 
   JsonPath = "";

   // for( var i =0; i< req.files.length; i++)
   // {
	  UploadoneFile(req ,res);	   
 //  }
  
  // console.log( "没有停下来" );
})
 app.get('/file_download',function(req, res){
	  var realPath = path.join(path.resolve() , "/upload/");
	var dPaht =  decodeURI(req.query.path);
	var fileName = decodeURI(req.query.name);
    var currDir = path.join(realPath,dPaht),
        
        currFile = path.join(currDir,fileName),
        fReadStream;
		console.log(fileName);
		console.log(dPaht);	
		console.log(currDir);	
	var downfile = function(currFile,fileName)
		{
			fs.exists(currFile,function(exist) {
			if(exist){
				res.set({
					"Content-type":"application/octet-stream",
					"Content-Disposition":"attachment;filename="+encodeURI(fileName)
				});
				fReadStream = fs.createReadStream(currFile);
				fReadStream.on("data",(chunk) => res.write(chunk,"binary"));
				fReadStream.on("end",function () {
					
					// const fd = fs.openSync(paths + '/' + item, 'r+');
					// var stats = fs.fstatSync(fd);
					// var strname = '{\"name\":\"' + ReFile+ '\",';
					// strname =strname + '\"Date\":\"' + stats.mtime+ '\",';
					// strname =strname + '\"Size\":\"' + stats.size+ '\",';
					
					// var filePath = path.join(path.resolve() , "/upload/");
					// var ReFile2 = "";
					// if(root == filePath)
					// {
						// ReFile2 = '';
					// }
					// else{
					 // ReFile2= getRedir(root,filePath);
					// }
					// strname =strname + '\"url\":\"'+ '/file_download?name=' + ReFile + '&path='+ ReFile2 + '\"},';
					// JsonPath = JsonPath + strname;
					// fs.closeSync(fd);
					resjson = {
					   Reslut:'0', 
					   Msg:'文件：' + fileName +' ,下载成功;'
				    };
					console.log(JSON.stringify( resjson ));
					//res.end(JSON.stringify( resjson )); // 如果在写文件的时候传递这个字符串 会把这段内容写到文件里面去。
					res.end();
					var myDate = new Date();
					console.log(myDate.getTime()); 
				});
				fReadStream.on("fReadStream.on",function(){
					resjson = {
					   Reslut:'-2', 
					   Msg:'文件：' + fileName +' ,数据传递错误;'
				    };
					console.log(JSON.stringify( resjson ));
					res.end(JSON.stringify( resjson )); 
					res.end();
				});
			}else{
				res.set("Content-type","text/html");
				//res.send("文件不存在!");
				resjson = {
					   Reslut:'-1', 
					   Msg:'下载文件：'+ fileName +' 不存在, 失败；'
				  };
				console.log(JSON.stringify( resjson ));
				res.end(JSON.stringify( resjson ));
			}
			if(bzip){
				fs.unlinkSync(currFile);
			}			
		});
	}	
		var bzip = false;
		if(fileName.length == 0 )// 没有 可能是下载文件夹
		{
			if(currDir.length != 0 )
			{
				//https://www.npmjs.com/package/zip-local
				// zipper.sync.zip(currDir).compress().save(currDir + ".zip");	
				// currFile = currDir + ".zip";
				// fileName = getRedir(currFile,'\\');
				// bzip = true;
				zipper.zip(currDir, function(error, zipped) { 
					if(!error) {
						zipped.compress(); // compress before exporting 				 
						var buff = zipped.memory(); // get the zipped file as a Buffer 				 
						// or save the zipped file to disk 
						zipped.save(currDir + ".zip", function(error) {
							if(!error) {
								console.log("saved zip successfully !");
								bzip = true;
								currFile = currDir + ".zip";
								fileName = getRedir(currFile,'\\');
								downfile(currFile,fileName);							
							}
						});
					}
				});				
			}
		}
		else{
			downfile(currFile,fileName);
		}
		
	
});
 app.get('/file_list/*',function(req, res){
	console.log(req.originalUrl);
	var dUrl = decodeURI(req.originalUrl);
	
	var ReFile = getRedir(dUrl,'/file_list/');
	var realPath = path.join(path.resolve() , "/upload/");
	var pathname = path.join(realPath, ReFile);
	console.log(pathname);
	if (pathname.charAt(pathname.length - 1) == "/") {
            //如果访问目录
		pathname += "index.html"; //指定为默认网页
	}
	else
	{
		try {
			
			fs.readFile( pathname, function (err, data) {        
		 if( err ){
			 pathname += "index.html"; //指定为默认网页
		 }else{
			 	//var ast= 'File uploaded successfully';
				//console.log( ast );	
				// var lastName = getdir(pathname);
// 　				res.writeHead(200,{'Content-Type' : 'text/html'});　					
				// res.write(data);
				res.writeHead(200,{'Content-Type' : 'text/plain'});					
				res.end(fs.readFileSync(pathname));　
				//res.end();　
			}
		   });	
		
		} catch(e) 
		{
			console.log('路径访问错误！');
		}
			
	}
   
 });
 
var server = app.listen(1024, '192.168.1.101',function () {
  var host = server.address().address
  var port = server.address().port
  Adrrs = 'http://' + host + ':'+ port;
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})
function UploadoneFile(req,response)
{	
	//console.log(req);

	if(req.files.length == 0 ) // 没有上传文件 
	{
		resjson = {
               Reslut:'-1', 
               Msg:'没有上传文件'
          };
		console.log( resjson );
        response.end( JSON.stringify( resjson ) );
		return;
	}
	var paths = decodeURI(req.body.path),
	    des_file = decodeURI(req.files[0].originalname),
		tempPaht = decodeURI(req.files[0].path),
		ziptype = decodeURI(req.body.ziptype);
	// 检测路径是否存在 ，
	var curPaht = __dirname + "/upload/" + paths;
	console.log("file_upload" + curPaht)
	fs.exists(curPaht,function(exists)
	{
		if(exists){
			console.log("文件夹存在")
			upcopyfile(des_file,ziptype,tempPaht,curPaht,response,paths);
		}
		else{
        console.log("文件夹不存在，创建")
		// if(!CheckPath(curPaht))
		// {
			 // resjson = {
               // Reslut:'-2', 
               // errMsg:'非法路径：'+ curPaht +' ; ' 
			// };
			// console.log( resjson );
			// response.end( JSON.stringify( resjson ) );
			// return;
		// }
		try{
			if(!mkdirsSync(curPaht)){
				// JsonPath =  '{\"Reslut\":"-2",\"files\":[{\"' + curPaht +'\":\"-2\"}]}';		 
				  // console.log( "文件夹不存在，创建失败！" +err );
				// response.write(JsonPath  );
				// response.end();
				  //return JsonPath;
				  resjson = {
				   Reslut:'-3', 
				   Msg:'创建路径：'+ paths +' ; 失败' 
				};
				console.log( resjson );
				response.end( JSON.stringify( resjson ) );
				return;
			};
		}
		catch(e)
		{
			 resjson = {
               Reslut:'-2', 
               Msg:'非法路径：'+ paths +' ;' 
			};
			console.log( resjson );
			response.end( JSON.stringify( resjson ) );
			return;
		}
		upcopyfile(des_file,ziptype,tempPaht,curPaht,response,paths);
      }
	});
	var upcopyfile = function(des_file,ziptype,tempPaht,curPaht,response,paths)
	{
		console.log( des_file );
		console.log( ziptype );
		var file = path.join(curPaht , des_file);
	    fs.readFile(tempPaht, function (err, data) {
			fs.writeFile(file, data, function (err) {
			 if( err ){	
				resjson = {
						   Reslut:'-1', 
						   Msg:'上传文件：'+ des_file +'失败 ;' 
						};			 
				// JsonPath =  '{\"Reslut\":"-1",\"Msg\":[{\"' + des_file +'\":\"-1\"}]}';
				  // console.log( err );
				  // response.write(JsonPath  );
				 // response.end();
				console.log( resjson );
				response.end( JSON.stringify( resjson ) );
				  return JsonPath;
			 }else{
				 // JsonPath =  '{\"Reslut\":"0",\"Msg\":[{\"' + des_file  +'\":\"0\"}]}' ;
				 // console.log(JsonPath );	
				 // response.write(JsonPath  );
				 // response.end();
				 resjson = {
						   Reslut:'0', 
						   Msg:'上传文件：'+ des_file +'成功 ;' 
						};	
				console.log( resjson );
				response.end( JSON.stringify( resjson ) );
				 if(ziptype == '1') // 上传的文件是需要解压的
				 {
					 try {
					 var unzip = new adm_zip(file);  
					 unzip.extractAllTo(curPaht, /*overwrite*/true);
					 }
					catch(e)
					{
						console.log('解压错误!!！');
					}
					
				 }
				 else if(paths == "bugzip")// 这个是往bug报告文档下存数据的 
				 {
					 AddSearchFile(curPaht,file);
				 }
				  return JsonPath;
			  }
			  // console.log( response );
			  // res.end( JSON.stringify( response ) );
		   });
	   }); 
	}
	
}


function AddSearchFile(cPaht,file)
{	
	// 解压文件 把所有的文本文件进行解压 把文本内容添加到json文件中 
	// 1 下载 服务器indexSeachfile
	var url = cPaht + "/indexSeachfile.txt";	

	var IndexSeachfiledata = fs.readFileSync(url,"utf-8"); 
	//IndexSeachfiledata = IndexSeachfiledata.substring(1,IndexSeachfiledata.length);
	console.log(IndexSeachfiledata);
	if(IndexSeachfiledata.length < 2)
	{
		IndexSeachfiledata= '[' +IndexSeachfiledata+']';
	}	
	var obj = JSON.parse(IndexSeachfiledata);

	console.log("1234AddSearchFile");	

//	console.log(IndexSeachfiledata);
	// 2 把当前文件写到服务文件中	
	// 2.1 解压当前压缩包
	var fpath = getFRedir(file,'.');
	
	var unzip = new adm_zip(file);  
	unzip.extractAllTo(fpath, /*overwrite*/true);
	//2.2 遍历文本
	//var textfile = function(Paht,response)
	//{
		
		if(fs.existsSync(fpath))
		{  
			files = fs.readdirSync(fpath); 
			var filetext='';
			files.forEach(function(file1, index)
			{  
				
				var curPath = fpath + "/" + file1;  
				
				if(fs.statSync(curPath).isDirectory())
				{ // recurse  
					//textfile(curPath,response);  
				} else
				{ 
				//	console.log(curPath);
				//	console.log("123");	
					var _text = getdir(curPath);
					//console.log(_text);	
					if(_text == "txt")
					{
						var fileStr = fs.readFileSync(curPath, {encoding:'binary'}); 
						
						var buf = new Buffer(fileStr, 'binary');  
  						var str = iconv.decode(buf, 'GBK');  
						// 需要替换掉其中的 回车 换行
						str=str.replace(/\r\n/g,"<BR>")  
						str=str.replace(/\n/g,"<BR>");    
						str=str.replace(/\"/g,"&quot;")	; // 引号 替换					
					//	console.log(str);  
						filetext +=str;
					//	console.log(filetext);						
					}
				}
			});
			// 获取文件的信息
			var ReFile = getRedir(file,'/');;		
			//console.log(ReFile);	
			const fd = fs.openSync(file, 'r+');
			var stats = fs.fstatSync(fd);
			var addjson= {
				"name":ReFile,
				"Date": FormatGmtData(stats.mtime),
				"Size":stats.size,
				"fData":filetext,
				"url":encodeURI('/file_download?name=' + ReFile + '&path='+ "bugzip")
			}
			// var strname = '{"name" :"' + ReFile+ '",';
			// strname =strname + '"Date":"' + FormatGmtData(stats.mtime)+ '",';
			// strname =strname + '"Size\":"' + stats.size+ '",';
			// strname =strname + '"fData\":"' + filetext + '",';
			// var filePath = path.join(path.resolve() , "/upload/");
						
			// strname =strname + '"url":"'+encodeURI('/file_download?name=' + ReFile + '&path='+ "bugzip") + '"}';
			// if(IndexSeachfiledata.length > 2)
			// {
				// IndexSeachfiledata = IndexSeachfiledata +","+ strname;
			// }
			// else
			// {
				// IndexSeachfiledata = IndexSeachfiledata + strname;
			// }
			fs.closeSync(fd);
			var bfind= false;
			for(var i = 0;i< obj.length;i++)
			{
				if(ReFile == obj[i].name)
				{
					obj[i].fData = filetext;
					bfind = true;
					break;
				}
			}
			if(!bfind)
			{
				//var addjson = JSON.parse(strname);
				obj.push(addjson);
			}
			// 2.2 找到所有文本文件，合并所有文本文件写到 indexSeachfile 中 
			fs.writeFileSync(url, JSON.stringify(obj),"utf-8");
			console.log(JSON.stringify(obj));
		}	
	//}
	// 3 删除 解压后的文件夹
	var rmdir = function (dirPath) {
	var files = fs.readdirSync(dirPath);
	if (files.length > 0)
	  for (var i = 0; i < files.length; i++) {
	   var filePath = path.join(dirPath, files[i]);
	   if (fs.statSync(filePath).isFile()) {
		fs.unlinkSync(filePath);
	   } else {
		rmdir(filePath);
	   }
	  }
	 fs.rmdirSync(dirPath);
	};
	rmdir(fpath);
}
function readText(pathname) {
    //var bin = fs.readFileSync(pathname);
//
  //  if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) {
    //    bin = bin.slice(3);
    //}

   // return bin.toString('utf-8');
        var fileStr = fs.readFileSync(pathname, {encoding:'binary'});

        var buf = new Buffer(fileStr, 'binary');
        var str = iconv.decode(buf, 'GBK');
        // 需要替换掉其中的 回车 换行
        str=str.replace(/\r\n/g,"<BR>")
        str=str.replace(/\n/g,"<BR>");
        str=str.replace(/\"/g,"&quot;") ; // 引号 替换
        return str;
}
 function DelSearchFile(cPaht,file)
 {
	 console.log("DelSearchFile");	
	 var url = cPaht + "/indexSeachfile.txt";	

	var IndexSeachfiledata = fs.readFileSync(url,"utf-8"); 
	//IndexSeachfiledata = IndexSeachfiledata.substring(1,IndexSeachfiledata.length);
	console.log(IndexSeachfiledata);
	if(IndexSeachfiledata.length < 2)
	{
		return;
	}	
	//var ReFile = getRedir(file,'/');
	var obj = JSON.parse(IndexSeachfiledata);
	for(var i = 0;i< obj.length;i++)
	{
		if(file == obj[i].name)
		{
			obj.splice(i,1);			
			break;
		}
	}
	fs.writeFileSync(url, JSON.stringify(obj),"utf-8");
	console.log(JSON.stringify(obj));
	
 }
function getfileinfon()
{
}
//递归创建目录 同步方法
function mkdirsSync(dirname) {
    //console.log(dirname);
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}
//递归创建目录 异步方法
function mkdirs(dirname, callback) {
    fs.exists(dirname, function (exists) {
        if (exists) {
            callback();
        } else {
            //console.log(path.dirname(dirname));
            mkdirs(path.dirname(dirname), function () {
                fs.mkdir(dirname, callback);
            });
        }
    });
}
// 递归删除文件夹 -- 异步方式
function deleteall(path,response) {  
    var files = [];  
    if(fs.existsSync(path)) {  
        files = fs.readdirSync(path);  
        files.forEach(function(file, index) {  
            var curPath = path + "/" + file;  
            if(fs.statSync(curPath).isDirectory()) { // recurse  
                deleteall(curPath,response);  
            } else { // delete file 
				var onrespons;
				//var as = fs.unlinkSync(curPath);
				//console.log('文件:'+as+'删除成功！');
				fs.unlink(curPath, function(err){
				 if(err){
				  //throw err;
				  berr = false;
				   onrespons = '{\"' + curPath +'\":\"-1\"}';
				   JsonPath = JsonPath + onrespons + ',';
				  // console.log(JsonPath);
				 }
				 else{
					onrespons = '{\"' + curPath +'\":\"0\"}';
				    JsonPath = JsonPath + onrespons + ',';
				 }
				// console.log('文件:'+curPath+'删除成功！');
				});
            }  
        });  
		// var onrespons;
        // fs.rmdirSync(path);
		// response = response + onrespons +",";	
		// console.log('文件:'+path+'删除成功！');	
		// console.log(response);	
		fs.rmdir(path, function(err){
		 if(err){
		 // console.log(err);
					var onrespons;
					berr = false;
				   onrespons = '{\"' + path +'\":\"-1\"}';
				   JsonPath = JsonPath + onrespons + ',';
				 //  console.log(JsonPath);
		 }else{
			onrespons = '{\"' + path +'\":\"0\"}';
			JsonPath = JsonPath + onrespons + ',';
		  //console.log(JsonPath);
		 }
		});		
    }  
	console.log('23'+ JsonPath);
}; 
function deletOneFile(file,response){
	fs.unlink(file, function(err){
		 if(err){
			response =  '{\"' + file  +'\":\"-1\"}';
			return -1;
		}
		else{
		  response =  '{\"' + file  +'\":\"0\"}';
		  return 0;
	    }
		 console.log('文件:'+file+'删除成功！');
	})	
	//fs.unlinkSync(file);
}	
function walkJson(paths,Name,root){
	var dirList = fs.readdirSync(paths);
	dirList.forEach(function(item){
		if(fs.statSync(paths + '/' + item).isDirectory()){
			walkJson(paths + '/' + item,Name,root);
			// var ReFile = getRedir(paths + '/' + item );
			// JsonPath = JsonPath + "\"" + ReFile + "/\",";			
		}else{		
			// 过滤按名称过滤字符串	
			//new RegExp(Name);
			try{
			var reg = 	new RegExp(Name);//eval('/'+Name+'/')	; // 动态生成字符串 正则匹配方式	
			}
			catch(e)
			{
				return;
			}
			if(reg.test(item)){
				// 获取文件的信息
				var ReFile = getRedir(paths + '/' + item,root);		

				const fd = fs.openSync(paths + '/' + item, 'r+');
				var stats = fs.fstatSync(fd);
				var strname = '{"name" :"' + ReFile+ '",';
				strname =strname + '"Date":"' + FormatGmtData(stats.mtime)+ '",';
				strname =strname + '"Size\":"' + stats.size+ '",';
				
				var filePath = path.join(path.resolve() , "/upload/");
				var ReFile2 = "";
				if(root == filePath)
				{
					ReFile2 = '';
				}
				else{
				 ReFile2= getRedir(root,filePath);
				}
				
				strname =strname + '"url":"'+encodeURI('/file_download?name=' + ReFile + '&path='+ ReFile2) + '"},';
				JsonPath = JsonPath + strname;
				fs.closeSync(fd);
				//console (stats);
			}	
		}			
	});
}
// 写入到filelisttxt文件
function writeFile(data){
	var data = data.join("\n");
	var filePath = path.resolve() + "/upload/";
	fs.writeFile(filePath+"/"+"filelist.txt",data+'\n',function(err){
    if(err) throw err;
    console.log(data);
  });
}
function getFRedir(url,root){
  var arr = url.split(root);
  var len = arr.length;
	var az = '';
	for(var i =0; i< len -1; i++)
	{
		az += arr[i] ;
		if(i != len-1 -1 ){
			az = az + root;
		}
	}
  return az;
}
function getRedir(url,root){
 //console.log(url);
  var arr = url.split(root);
  var len = arr.length;
//  console.log(arr[len-1]);
  return arr[len-1];
}
//获取后缀名
function getdir(url){
  var arr = url.split('.');
  var len = arr.length;
  return arr[len-1];
}
function FormatGmtData(str)
{
	str = str.toString();
	str = str.replace(/ GMT.+$/, '');// Or str = str.substring(0, 24)
	var d = new Date(str);
	var a = [d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()];
	for(var i = 0, len = a.length; i < len; i ++) {
		if(a[i] < 10) {
			a[i] = '0' + a[i];
		}
	}
	str = a[0] + '-' + a[1] + '-' + a[2] + ' ' + a[3] + ':' + a[4] + ':' + a[5];
	return str;
}